package com.zhang.d_direct;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class B_consumer1 {


    //这是程序的入口
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建Connection
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.200.114");
        factory.setPort(5672);
        factory.setVirtualHost("/");
        factory.setUsername("guest");
        factory.setPassword("guest");
        Connection connection = factory.newConnection();


        //2.创建channel
        Channel channel = connection.createChannel();

        //限制消费者每次只能接受一条消息，处理完才能接受下一条消息        
        channel.basicQos(1);

        //3.创建队列
        channel.queueDeclare("q1",true,false,false,null);


        //4.监听队列
        //(1)当收到消息后执行该方法
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            //模拟消费耗时
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println("监听q1队列的消费者1 收到消息: "+message);
        };

        //(2)接收消息
        channel.basicConsume("q1", true, deliverCallback, consumerTag -> { });
    }
}
